//设置缓存数据
export const setStorage = function(key, value) {
	uni.setStorage({
		key: key,
		data: value
	})
}


//点击节流事件，防止重复点击事件
export const throttle = function(fn,gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 1500
	}
	let _lastTime = null
	// 返回新的函数
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments) //将this和参数传给原函数
			_lastTime = _nowTime
		}
	}
}

//获取缓存数据
export const getStorage = function(key, callback) {
	uni.getStorage({
		key: key,
		success(res) {
			callback(res.data);
		}
	})
}
//显示loading
export const showLoading = function(content) {
	uni.showLoading({
		title: content,
		mask: true
	})
}

//防抖
export const debounce = function(fn, delay) {
	let timer = null; //借助闭包
	return function() {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(fn, delay); // 简化写法
	}
}

export const showModal = function(content, callback = function() {}, showCancel = false, confirmText = "确定") {
	uni.showModal({
		title: '提示',
		content: content,
		showCancel: showCancel,
		confirmText: confirmText,
		success(res) {
			if (res.confirm) {
				callback();
			}
		}
	});
}
//获取当前时间时分秒，毫秒
export const getNowTime = function() {
	let date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let date2 = date.getDate();
	let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
	let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	let milliSeconds = date.getMilliseconds();
	let currentTime = year + '-' + month + '-' + date2 + ' ' + hour + ':' + minute + ':' + second +
		'.' + milliSeconds;
	return currentTime;
}
//添加睡眠时间
export const sleep = function(time) {
	var startTime = new Date().getTime() + parseInt(time, 10);
	while (new Date().getTime() < startTime) {}
}

export const navigateTo = function(url) {
	wx.navigateTo({
		url: url
	});
}

export const unique = function(arr, name) {
	const res = new Map();
	return arr.filter((a) => !res.has(a[name]) && res.set(a[name], 1))
}

//验证
export const validate = function(str, type) {
	let reg = /^.*$/;
	switch (type) {
		case "ip":
			reg =
				/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
			break;
		case "port":
			reg = /^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-6][0-5][0-5][0-3][0-5]$)/;
			break;
		case "number":
			reg = /^[0-9]*$/
			break;
		default:
	}
	return reg.test(str);
}
